package me.zhengjie.modules.company.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.AllArgsConstructor;
import me.zhengjie.base.PageInfo;
import me.zhengjie.base.QueryHelpMybatisPlus;
import me.zhengjie.base.impl.CommonServiceImpl;
import me.zhengjie.config.FileProperties;
import me.zhengjie.domain.LocalStorage;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.banner.domain.Banner;
import me.zhengjie.modules.system.domain.DictDetail;
import me.zhengjie.modules.system.service.mapper.DictDetailMapper;
import me.zhengjie.service.mapper.LocalStorageMapper;
import me.zhengjie.utils.ConvertUtil;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.modules.company.domain.Company;
import me.zhengjie.modules.company.service.CompanyService;
import me.zhengjie.modules.company.service.dto.CompanyDto;
import me.zhengjie.modules.company.service.dto.CompanyQueryParam;
import me.zhengjie.modules.company.service.mapper.CompanyMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
// 默认不使用缓存
//import org.springframework.cache.annotation.CacheConfig;
//import org.springframework.cache.annotation.CacheEvict;
//import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Pageable;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
* @author TianI
* @date 2022-01-21
*/
@Service
@AllArgsConstructor
// @CacheConfig(cacheNames = CompanyService.CACHE_KEY)
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class CompanyServiceImpl extends CommonServiceImpl<CompanyMapper, Company> implements CompanyService {
    private final DictDetailMapper detailMapper;
    private final FileProperties properties;
    private final CompanyMapper companyMapper;
    private final LocalStorageMapper localStorageMapper;
    @Override
    public PageInfo<CompanyDto> queryAll(CompanyQueryParam query, Pageable pageable) {
        IPage<Company> queryPage = PageUtil.toMybatisPage(pageable);
        IPage<Company> page = companyMapper.selectPage(queryPage, QueryHelpMybatisPlus.getPredicate(query));
        return ConvertUtil.convertPage(page, CompanyDto.class);
    }

    @Override
    public List<CompanyDto> queryAll(CompanyQueryParam query){
        return ConvertUtil.convertList(companyMapper.selectList(QueryHelpMybatisPlus.getPredicate(query)), CompanyDto.class);
    }

    @Override
    public Company getById(Long id) {
        return companyMapper.selectById(id);
    }

    @Override
    // @Cacheable(key = "'id:' + #p0")
    public CompanyDto findById(Long id) {
        return ConvertUtil.convert(getById(id), CompanyDto.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(CompanyDto resources) {
        Company entity = ConvertUtil.convert(resources, Company.class);
        entity.setCompanyId(RandomUtil.randomLong(10));
        entity.getCompanyName();
        DictDetail dictDetail = new DictDetail();
        dictDetail.setCreateBy("admin");
        dictDetail.setDictId(6L);
        dictDetail.setDictSort(999);
        dictDetail.setValue(entity.getCompanyId().toString());
        dictDetail.setLabel(entity.getCompanyName());
        detailMapper.insert(dictDetail);
        return companyMapper.insert(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateById(CompanyDto resources){
        Company entity = ConvertUtil.convert(resources, Company.class);
        int ret = companyMapper.updateById(entity);
        // delCaches(resources.id);
        return ret;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeByIds(Set<Long> ids){
        // delCaches(ids);
        return companyMapper.deleteBatchIds(ids);
    }

    @Override
    public Company createImg(MultipartFile multipartFile) {
        FileUtil.checkSize(properties.getMaxSize(), multipartFile.getSize());
        String suffix = FileUtil.getExtensionName(multipartFile.getOriginalFilename());
        String type = FileUtil.getFileType(suffix);
        File file = FileUtil.upload(multipartFile, properties.getPath().getPath() + type +  File.separator);
        if(ObjectUtil.isNull(file)){
            throw new BadRequestException("上传失败");
        }
        try {
            String name = file.getName();
            LocalStorage localStorage = new LocalStorage(
                    file.getName(),
                    name,
                    suffix,
                    file.getPath(),
                    type,
                    FileUtil.getSize(multipartFile.getSize())
            );
            localStorageMapper.insert(localStorage);
            Company company = new Company();
            company.setCompanyBrandLogoUrl(file.getName());
            return company;
        }catch (Exception e){
            FileUtil.del(file);
            throw e;
        }
    }
    @Override
    public Company createBanner(MultipartFile multipartFile) {
        FileUtil.checkSize(properties.getMaxSize(), multipartFile.getSize());
        String suffix = FileUtil.getExtensionName(multipartFile.getOriginalFilename());
        String type = FileUtil.getFileType(suffix);
        File file = FileUtil.upload(multipartFile, properties.getPath().getPath() + type +  File.separator);
        if(ObjectUtil.isNull(file)){
            throw new BadRequestException("上传失败");
        }
        try {
            String name = file.getName();
            LocalStorage localStorage = new LocalStorage(
                    file.getName(),
                    name,
                    suffix,
                    file.getPath(),
                    type,
                    FileUtil.getSize(multipartFile.getSize())
            );
            localStorageMapper.insert(localStorage);
            Company company = new Company();
            company.setCompanyBannerUrl(file.getName());
            return company;
        }catch (Exception e){
            FileUtil.del(file);
            throw e;
        }
    }
    @Override
    public Company createVideo(MultipartFile multipartFile) {
        FileUtil.checkSize(properties.getMaxSize(), multipartFile.getSize());
        String suffix = FileUtil.getExtensionName(multipartFile.getOriginalFilename());
        String type = FileUtil.getFileType(suffix);
        File file = FileUtil.upload(multipartFile, properties.getPath().getPath() + type +  File.separator);
        if(ObjectUtil.isNull(file)){
            throw new BadRequestException("上传失败");
        }
        try {
            String name = file.getName();
            LocalStorage localStorage = new LocalStorage(
                    file.getName(),
                    name,
                    suffix,
                    file.getPath(),
                    type,
                    FileUtil.getSize(multipartFile.getSize())
            );
            localStorageMapper.insert(localStorage);
            Company company = new Company();
            company.setCompanyVideoUrl(file.getName());
            return company;
        }catch (Exception e){
            FileUtil.del(file);
            throw e;
        }
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeById(Long id){
        Set<Long> set = new HashSet<>(1);
        set.add(id);
        return this.removeByIds(set);
    }

    /*
    private void delCaches(Long id) {
        redisUtils.delByKey(CACHE_KEY + "::id:", id);
    }

    private void delCaches(Set<Long> ids) {
        for (Long id: ids) {
            delCaches(id);
        }
    }*/


    @Override
    public void download(List<CompanyDto> all, HttpServletResponse response) throws IOException {
      List<Map<String, Object>> list = new ArrayList<>();
      for (CompanyDto company : all) {
        Map<String,Object> map = new LinkedHashMap<>();
              map.put("总公司名称", company.getCompanyName());
              map.put("总公司品牌logo路径", company.getCompanyBrandLogoUrl());
              map.put("总公司首页展示视频路径", company.getCompanyVideoUrl());
              map.put("创建时间", company.getCreateTime());
              map.put("更新时间", company.getUpdateTime());
              map.put("手机号", company.getPhone());
        list.add(map);
      }
      FileUtil.downloadExcel(list, response);
    }


}
